package com.boot.security.server.service.impl;

import com.boot.security.server.common.Result;
import com.boot.security.server.common.ResultBuilder;
import com.boot.security.server.dao.RoleDao;
import com.boot.security.server.dto.LoginUser;
import com.boot.security.server.dto.RoleDto;
import com.boot.security.server.mapper.SysPermissionMapper;
import com.boot.security.server.mapper.SysRoleMapper;
import com.boot.security.server.mapper.SysRolePermissionMapper;
import com.boot.security.server.mapper.SysRoleUserMapper;
import com.boot.security.server.mapper.domain.SysMapper;
import com.boot.security.server.model.Role;
import com.boot.security.server.model.domain.SysPermission;
import com.boot.security.server.model.domain.SysRole;
import com.boot.security.server.model.domain.SysRolePermission;
import com.boot.security.server.model.domain.SysRoleUser;
import com.boot.security.server.service.RoleService;
import com.boot.security.server.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {

    private static final Logger log = LoggerFactory.getLogger("adminLogger");

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysMapper sysMapper;


    @Override
    @Transactional
    public void saveRole(RoleDto roleDto) {
        Role role = roleDto;
        List<Long> permissionIds = roleDto.getPermissionIds();
        permissionIds.remove(0L);

        if (role.getId() != null) {// 修改
            updateRole(role, permissionIds);
        } else {// 新增
            saveRole(role, permissionIds);
        }
    }

    private void saveRole(Role role, List<Long> permissionIds) {
        Role r = roleDao.getRole(role.getName());
        if (r != null) {
            throw new IllegalArgumentException(role.getName() + "已存在");
        }

        roleDao.save(role);
        if (!CollectionUtils.isEmpty(permissionIds)) {
            roleDao.saveRolePermission(role.getId(), permissionIds);
        }
        log.debug("新增角色{}", role.getName());
    }

    private void updateRole(Role role, List<Long> permissionIds) {
        Role r = roleDao.getRole(role.getName());
        if (r != null && r.getId() != role.getId()) {
            throw new IllegalArgumentException(role.getName() + "已存在");
        }

        roleDao.update(role);

        roleDao.deleteRolePermission(role.getId());
        if (!CollectionUtils.isEmpty(permissionIds)) {
            roleDao.saveRolePermission(role.getId(), permissionIds);
        }
        log.debug("修改角色{}", role.getName());
    }

    @Override
    @Transactional
    public void deleteRole(Long id) {
        roleDao.deleteRolePermission(id);
        roleDao.deleteRoleUser(id);
        roleDao.delete(id);

        log.debug("删除角色id:{}", id);
    }

    @Override
    public String getRoleName() {
        LoginUser loginUser = UserUtil.getLoginUser();
        return roleDao.findByUserId(loginUser.getId());
    }
     /**
      * @Author Ming
      * @Date 2020/11/11 11:43
      * @Description 查询角色列表
      **/
    @Override
    public List<SysRole> getRoleList() {

        return sysRoleMapper.selectAll();
    }

     /**
      * @Author Ming
      * @Date 2020/11/11 15:47
      * @Description 查询角色拥有的权限
      **/
    @Override
    public List<SysPermission> getPurviewList(Integer id) {


       List<SysPermission> permissions = roleDao.getPurviewList(id);

        return permissions;

    }

     /**
      * @Author Ming
      * @Date 2020/11/11 18:03
      * @Description 保存角色
      **/
    @Override
    public Result addRole(SysRole param) {
        param.setCreatetime(new Date());
        param.setUpdatetime(new Date());
        try {
            sysRoleMapper.insertSelective(param);
        } catch (Exception e) {
           return ResultBuilder.paramError("已存在相同的用户名");
        }
        return ResultBuilder.success();
    }

     /**
      * @Author Ming
      * @Date 2020/11/12 10:56
      * @Description  删除角色
      **/
    @Override
    public Result delRole(Integer id) {
        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setRoleid(id);
        List<SysRoleUser> select = sysRoleUserMapper.select(sysRoleUser);
        if (select.size() > 0){
            return ResultBuilder.paramError("角色使用中，无法删除");
        }
        SysRolePermission permission = new SysRolePermission();
        permission.setRoleid(id);
        sysRolePermissionMapper.delete(permission);

        sysRoleMapper.deleteByPrimaryKey(id);
        return ResultBuilder.success();
    }

     /**
      * @Author Ming
      * @Date 2020/11/12 14:28
      * @Description 获取所有菜单权限
      **/
    @Override
    public List<SysPermission> getAllPurview() {
        return roleDao.getAll();
    }
     /**
      * @Author Ming
      * @Date 2020/11/12 17:30
      * @Description  关闭权限
      **/
    @Override
    public void coles(Integer roleid, Integer pid,Integer parentId) {
        // 此权限下级菜单id
        SysPermission sysPermission = new SysPermission();
        sysPermission.setParentid(pid);
        List<SysPermission> select = sysPermissionMapper.select(sysPermission);



        List<Integer> pids = select.stream().map(SysPermission::getId).collect(Collectors.toList());
        pids.add(pid);

        int num = roleDao.query(roleid,parentId);
        if (num < 2){
            pids.add(parentId);
        }

        for (Integer integer : pids) {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setPermissionid(integer);
            sysRolePermission.setRoleid(roleid);
            sysRolePermissionMapper.delete(sysRolePermission);
        }



    }

     /**
      * @Author Ming
      * @Date 2020/11/12 17:30
      * @Description  启用权限
      **/

    @Override
    public void open(Integer roleid, Integer pid,Integer parentId) {
        // 此权限下级菜单id
        SysPermission sysPermission = new SysPermission();
        sysPermission.setParentid(pid);
        List<SysPermission> select = sysPermissionMapper.select(sysPermission);

        List<Integer> pids = select.stream().map(SysPermission::getId).collect(Collectors.toList());
        pids.add(pid);
        SysRolePermission permission = new SysRolePermission();
        permission.setPermissionid(parentId);
        permission.setRoleid(roleid);
        SysRolePermission sysRolePermission1 = sysRolePermissionMapper.selectOne(permission);
        if (sysRolePermission1 == null){
            pids.add(parentId);
        }


        for (Integer integer : pids) {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setPermissionid(integer);
            sysRolePermission.setRoleid(roleid);
            sysRolePermissionMapper.insert(sysRolePermission);
        }

    }


}
